/* eslint-disable react/jsx-key */
/* eslint-disable react-hooks/exhaustive-deps */
import { getFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import React, { useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import { Divider, Skeleton, Button, Input, Upload, message, Modal } from 'antd';
import { PlusOutlined, FileImageOutlined } from '@ant-design/icons';
import ChartItem from '@/components/ChartItem';
import { OfficePreview, RemoteTxtFilePreview } from './office';
import Recorder from '@/components/Recorder';
import ChatRecord from '@/components/ChatRecord';
import CompanyDetail from '@/components/CompanyDetail';
import './index.less';

function Chat({ curitem, socket, addon }) {
  const [pageIndex, setPageIndex] = useState(null);
  const [data, setData] = useState([]);
  const [val, onChange] = useState();
  const { loading, ...other } = useRequest(
    async () => {
      if (!curitem?.id || !pageIndex) {
        return;
      }
      let res = await getFetch({
        url: '/wbn-api/wechat/employee/chat_message',
        params: {
          company_id: curitem?.id,
          pageIndex,
        },
      });
      return res?.data ?? {};
    },
    {
      refreshDeps: [pageIndex],
      debounceWait: 400,
      onSuccess: (res) => {
        const thisresult = res?.list ?? [];
        setData((s) => [...s, ...thisresult]);
      },
    },
  );

  const loadMoreData = () => {
    setPageIndex((s) => s + 1);
  };

  //change item
  useEffect(() => {
    setData([]);
    setPageIndex(null);
    setTimeout(() => {
      setPageIndex(1);
    }, 100);
  }, [curitem?.id]);

  //new msg
  useEffect(() => {
    if (addon?.company_id == curitem?.id || !addon?.company_id) {
      setData((s) => [addon, ...s]);
    }
  }, [addon, curitem]);

  const [isopen, setIsopen] = useState(false);

  const [modal, setModal] = useState({
    open: false,
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  return (
    <div
      style={{
        height: 'calc(100vh - 106px)',
        display: 'flex',
        flexDirection: 'column',
        position: 'relative',
      }}
    >
      <Modal
        {...modal}
        width={'calc(100vw - 40px)'}
        footer={false}
        style={{ top: 20 }}
        destroyOnClose={true}
      >
        {modal?.type === 'txt' ? (
          <div className="centerl">
            <RemoteTxtFilePreview url={modal.url} />
          </div>
        ) : modal?.type === 'mp3' ? (
          <div className="center">
            <audio src={modal?.url} controls />
          </div>
        ) : modal?.type === 'mp4' ? (
          <video
            src={modal?.url}
            controls
            style={{ width: '100%', height: 'calc(100vh - 110px)' }}
          />
        ) : modal?.type === 'detail' ? (
          <CompanyDetail id={curitem?.id} />
        ) : (
          <OfficePreview url={modal?.url} type={modal?.type} name={modal?.title} />
        )}
      </Modal>

      <div
        style={{
          position: 'absolute',
          top: 20,
          width: '100%',
        }}
        className="center"
      >
        <Button
          style={{ display: !curitem?.id ? 'none' : 'block' }}
          type="primary"
          size="small"
          onClick={() => {
            setModal((s) => ({
              ...s,
              title: '详细信息',
              type: 'detail',
              open: true,
            }));
          }}
        >
          详细信息
        </Button>
      </div>
      {!curitem?.id ? (
        <div
          id="scrollableDiv"
          style={{
            flex: 1,
            overflow: 'auto',
            width: '100%',
            display: 'flex',
            flexDirection: 'column-reverse',
          }}
        />
      ) : (
        <div
          id="scrollableDives"
          style={{
            flex: 1,
            overflow: 'auto',
            width: '100%',
            display: 'flex',
            flexDirection: 'column-reverse',
          }}
        >
          <InfiniteScroll
            dataLength={data?.filter?.((it) => it).length}
            next={loadMoreData}
            hasMore={other?.data?.hasnextpage}
            loader={
              <Skeleton
                avatar
                paragraph={{
                  rows: 1,
                }}
                active
              />
            }
            endMessage={<Divider plain>顶部</Divider>}
            scrollableTarget="scrollableDives"
            inverse={true}
            style={{ display: 'flex', flexDirection: 'column-reverse' }}
          >
            {data
              ?.filter?.((it) => it)
              ?.map((it, i) => {
                return <ChartItem {...it} setModal={setModal} modal={modal} />;
              })}
          </InfiniteScroll>
        </div>
      )}

      <div className="footer">
        <div className="center" style={{ gap: 12 }}>
          <Input
            disabled={!curitem?.id}
            size="large"
            bordered={false}
            placeholder="发送文本"
            value={val}
            onChange={(e) => {
              onChange(e.target.value);
            }}
            style={{ backgroundColor: '#fff', height: 40, flex: 1, borderRadius: 6 }}
            onPressEnter={(e) => {
              socket.emit(
                'user-message',
                JSON.stringify({
                  company_id: curitem?.id,
                  message_type: 'text',
                  message_content: e.target.value,
                }),
                (val) => {
                  onChange();
                },
              );
            }}
          />
          <Button
            size="large"
            type="text"
            style={{ backgroundColor: '#fff', border: 'none', borderRadius: 6 }}
            icon={<PlusOutlined rotate={isopen ? 45 : 0} />}
            disabled={!curitem?.id}
            onClick={() => {
              setIsopen(!isopen);
            }}
          />
        </div>
        <div className="actionbar" style={{ height: isopen ? 'auto' : 0, overflow: 'hidden' }}>
          <div style={{ width: '100%', height: 12 }} />
          <div className="centerl" style={{ gap: 12 }}>
            <Upload
              key="pic"
              name="file"
              listType="picture-card"
              style={{
                height: 'auto',
                width: 'auto',
                border: 'none',
                padding: 12,
                borderRadius: 8,
                backgroundColor: '#fff',
              }}
              showUploadList={false}
              action={window?.dataconfig?.serverURL}
              beforeUpload={(file) => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                  message.error('仅支持 JPG/PNG 文件!');
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  message.error('图片需要小于 2MB!');
                }
                return isJpgOrPng && isLt2M;
              }}
              onChange={(info) => {
                if (info.file.status === 'uploading') {
                  return;
                }
                if (info.file.status === 'done') {
                  // Get this url from response in real world.
                  const url = info?.file?.response?.data?.origin_url;
                  socket.emit(
                    'user-message',
                    JSON.stringify({
                      company_id: curitem?.id,
                      message_type: 'picture',
                      message_content: url,
                    }),
                  );
                }
              }}
            >
              <img style={{ width: 32, height: 32 }} src={require('@/assets/image.svg')} alt="" />
            </Upload>
            <Upload
              key="pic"
              name="file"
              listType="picture-card"
              style={{
                height: 'auto',
                width: 'auto',
                border: 'none',
                padding: 12,
                borderRadius: 8,
                backgroundColor: '#fff',
              }}
              showUploadList={false}
              action={window?.dataconfig?.serverURL}
              beforeUpload={(file) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  message.error('图片需要小于 2MB!');
                }
                return isLt2M;
              }}
              onChange={(info) => {
                if (info.file.status === 'uploading') {
                  return;
                }
                if (info.file.status === 'done') {
                  // Get this url from response in real world.
                  const url = info?.file?.response?.data?.origin_url;
                  socket.emit(
                    'user-message',
                    JSON.stringify({
                      company_id: curitem?.id,
                      message_type: 'file',
                      message_content: url,
                    }),
                  );
                }
              }}
            >
              <img style={{ width: 32, height: 32 }} src={require('@/assets/file.svg')} alt="" />
            </Upload>
            <Recorder socket={socket} company_id={curitem?.id} />
            <ChatRecord curitem={curitem} />
          </div>
        </div>
      </div>
    </div>
  );
}

export default Chat;
